﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Net;
using System.Xml;
using System.Text;
using System.IO;
namespace LHWebApp.Json
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class JsonGetVehicleHistoryInfoList : IHttpHandler
    {
        //houruixian 2018.07.16 
        List<HistoryVehicleEntity> historyVehicleList = new List<HistoryVehicleEntity>();
        HistoryVehicleEntity historyVehicle = null;

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string startDate = context.Request.Params["startDate"];
            string endDate = context.Request.Params["endDate"];
            string vid = context.Request.Params["vid"];
            if (string.IsNullOrEmpty(vid))
            {
                context.Response.Write("{success: false}");
            }
            else
            {
                try
                {
                    DataTable dt = LHWebApp.Services.GetVehicleHistoryInfoList(startDate, endDate, int.Parse(vid)).Tables[0];
                    JSONHelper jsonHelp = new JSONHelper();
                    jsonHelp.success = true;
                    jsonHelp.totlalCount = dt.Rows.Count;

                    if (jsonHelp.totlalCount == 0)
                    {
                        context.Response.Write("{success: true}");
                    }
                    else
                    {
                        //2018.07.16 百度地图经纬度矫正展示
                        foreach (DataRow dr in dt.Rows)
                        {

                            historyVehicle = new HistoryVehicleEntity();
                            historyVehicle.Lng = dr["Lng"].ToString();
                            historyVehicle.Lat = dr["Lat"].ToString();
                            historyVehicle.Speed = dr["Speed"].ToString();
                            historyVehicle.Direction = dr["Direction"].ToString();
                            historyVehicle.GpsTime = dr["GpsTime"].ToString();
                            historyVehicle.Status = dr["Status"].ToString();
                            historyVehicle.Location = dr["Location"].ToString();
                            historyVehicle.LngOffset = dr["LngOffset"].ToString();
                            historyVehicle.LatOffset = dr["LatOffset"].ToString();

                            historyVehicleList.Add(historyVehicle);

                        }

                        AdjustBaiduLongLat(historyVehicleList);
                        for (int i = 0; i < historyVehicleList.Count; i++)
                        {
                            jsonHelp.AddItem("Lng", historyVehicleList[i].Lng);
                            jsonHelp.AddItem("Lat", historyVehicleList[i].Lat);
                            jsonHelp.AddItem("Speed", historyVehicleList[i].Speed);
                            jsonHelp.AddItem("Direction", historyVehicleList[i].Direction);
                            jsonHelp.AddItem("GpsTime", historyVehicleList[i].GpsTime);
                            jsonHelp.AddItem("Status", historyVehicleList[i].Status);
                            jsonHelp.AddItem("Location", historyVehicleList[i].Location);
                            jsonHelp.AddItem("LngOffset", historyVehicleList[i].LngOffset);
                            jsonHelp.AddItem("LatOffset", historyVehicleList[i].LatOffset);
                            jsonHelp.ItemOk();
                        }

                        context.Response.Write(jsonHelp.ToString());
                    }
                }
                catch (Exception)
                {
                    context.Response.Write("{success: false}");
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        //2018.07.13 houruixian 百度地图经纬度矫正
        public void AdjustBaiduLongLat(List<HistoryVehicleEntity> lists)
        {
            int count = lists.Count / 100 + 1;
            string[] rawPoints = new string[count];
            for (int i = 0; i < count; i++)
            {
                rawPoints[i] = "";
            }
            List<HistoryVehicleEntity> historyLists = new List<HistoryVehicleEntity>();

            for (int i = 0; i < count; i++)
            {
                if (i < count - 1)
                {
                    for (int j = 0; j < 100; j++)
                    {
                        rawPoints[i] = rawPoints[i] + ";" + lists[j + i * 100].Lng + "," + lists[j + i * 100].Lat;
                    }
                }
                else
                {
                    for (int j = 0; j < lists.Count - 100 * (count - 1); j++)
                    {
                        rawPoints[i] = rawPoints[i] + ";" + lists[j + i * 100].Lng + "," + lists[j + i * 100].Lat;
                    }
                }
            }

            for (int i = 0; i < rawPoints.Length; i++)
            {
                rawPoints[i] = rawPoints[i].Substring(1, rawPoints[i].Length - 1);
            }

            for (int i = 0; i < count; i++)
            {
                historyLists = getBaiduLongLat(rawPoints[i]);
                if (i < count - 1)
                {
                    for (int j = 0; j < 100; j++)
                    {
                        historyVehicleList[j + i * 100].Lat = historyLists[j].Lat;
                        historyVehicleList[j + i * 100].Lng = historyLists[j].Lng;

                    }
                }
                else
                {
                    for (int j = 0; j < lists.Count - 100 * (count - 1); j++)
                    {
                        historyVehicleList[j + i * 100].Lat = historyLists[j].Lat;
                        historyVehicleList[j + i * 100].Lng = historyLists[j].Lng;
                    }
                }
            }

        }

        public List<HistoryVehicleEntity> getBaiduLongLat(string rawListStr)
        {
            List<HistoryVehicleEntity> historyLists = new List<HistoryVehicleEntity>();
            HistoryVehicleEntity historyEntity = null;

            string url = @"http://api.map.baidu.com/geoconv/v1/?coords=" + rawListStr + @"&from=1&to=5&ak=4HzsadCh4FDh1Eukq2shC3WT&output=xml";
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            XmlDocument xmlDoc = new XmlDocument();
            string sendData = xmlDoc.InnerXml;
            byte[] byteArray = Encoding.Default.GetBytes(sendData);

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, System.Text.Encoding.GetEncoding("utf-8"));
            string responseXml = reader.ReadToEnd();

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(responseXml);
            string status = xml.DocumentElement.SelectSingleNode("status").InnerText;
            if (status == "0")
            {
                XmlNodeList pointnodes = xml.DocumentElement.GetElementsByTagName("point");

                foreach (XmlNode node in pointnodes)
                {
                    historyEntity = new HistoryVehicleEntity();
                    XmlNodeList XNodes = ((XmlElement)node).GetElementsByTagName("x");  //获取age子XmlElement集合  
                    if (XNodes.Count == 1)
                    {
                        historyEntity.Lng = XNodes[0].InnerText;
                    }
                    XmlNodeList YNodes = ((XmlElement)node).GetElementsByTagName("y");  //获取age子XmlElement集合  
                    if (YNodes.Count == 1)
                    {
                        historyEntity.Lat = YNodes[0].InnerText;
                    }

                    historyLists.Add(historyEntity);
                }
            }

            return historyLists;
        }
       

    }
}
